package com.jyw.web.controller.system;

import com.jyw.common.annotation.Anonymous;
import com.jyw.common.annotation.Log;
import com.jyw.common.core.controller.BaseController;
import com.jyw.common.core.domain.AjaxResult;
import com.jyw.common.core.domain.CommonResult;
import com.jyw.common.core.domain.entity.SysDictData;
import com.jyw.common.core.page.TableDataInfo;
import com.jyw.common.enums.BusinessType;
import com.jyw.common.utils.DictUtils;
import com.jyw.common.utils.StringUtils;
import com.jyw.common.utils.poi.ExcelUtil;
import com.jyw.system.domain.vo.DictCacheListVo;
import com.jyw.system.service.ISysDictDataService;
import com.jyw.system.service.ISysDictTypeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 数据字典信息
 * 
 * @author system
 */
@RestController
@RequestMapping("/system/dict/data")
@Api(tags = "字典数据信息")
public class SysDictDataController extends BaseController
{
    @Resource
    private ISysDictDataService dictDataService;

    @Resource
    private ISysDictTypeService dictTypeService;

    @GetMapping("/list")
    @ApiOperation("字典数据列表")
    public TableDataInfo<SysDictData> list(SysDictData dictData)
    {
        startPage();
        List<SysDictData> list = dictDataService.selectDictDataList(dictData);
        return getDataTable(list);
    }

    @Log(title = "字典数据", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysDictData dictData)
    {
        List<SysDictData> list = dictDataService.selectDictDataList(dictData);
        ExcelUtil<SysDictData> util = new ExcelUtil<SysDictData>(SysDictData.class);
        util.exportExcel(response, list, "字典数据");
    }

    /**
     * 查询字典数据详细
     */
    @GetMapping(value = "/{dictCode}")
    @ApiOperation("字典数据详情")
    public AjaxResult getInfo(@PathVariable Long dictCode)
    {
        return success(dictDataService.selectDictDataById(dictCode));
    }

    /**
     * 根据字典类型查询字典数据信息
     */
    @GetMapping(value = "/type/{dictType}")
    @ApiOperation("根据字典类型查询字典数据信息")
    public AjaxResult dictType(@PathVariable String dictType)
    {
        List<SysDictData> data = dictTypeService.selectDictDataByType(dictType);
        if (StringUtils.isNull(data))
        {
            data = new ArrayList<SysDictData>();
        }
        return success(data);
    }

    /**
     * 新增字典数据
     */
    @PreAuthorize("@ss.hasPermi('system:dict:data:add')")
    @Log(title = "字典数据", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation("新增字典数据")
    public AjaxResult add(@Validated @RequestBody SysDictData dict)
    {
        dict.setCreateBy(getUsername());
        return toAjax(dictDataService.insertDictData(dict));
    }

    /**
     * 修改保存字典数据
     */
    @PreAuthorize("@ss.hasPermi('system:dict:data:edit')")
    @Log(title = "字典数据", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation("修改字典数据")
    public AjaxResult edit(@Validated @RequestBody SysDictData dict)
    {
        dict.setUpdateBy(getUsername());
        return toAjax(dictDataService.updateDictData(dict));
    }

    /**
     * 删除字典类型
     */
    @PreAuthorize("@ss.hasPermi('system:dict:data:remove')")
    @Log(title = "字典类型", businessType = BusinessType.DELETE)
    @DeleteMapping("/{dictCodes}")
    @ApiOperation("删除字典数据")
    public AjaxResult remove(@PathVariable Long[] dictCodes)
    {
        dictDataService.deleteDictDataByIds(dictCodes);
        return success();
    }


    /**
     * 新增字典数据
     */
    @PreAuthorize("@ss.hasPermi('system:dict:save')")
    @Log(title = "字典数据", businessType = BusinessType.INSERT)
    @PostMapping("save")
    @ApiOperation("保存字典数据")
    public CommonResult add(@Validated @RequestBody List<SysDictData> dictList)
    {
        dictList.forEach(data->{
            if(ObjectUtils.isEmpty(data.getDictCode())){
                data.setCreateBy(getUsername());
            }else {
                data.setUpdateBy(getUsername());
            }
        });
        if (dictDataService.saveOrUpdateBatch(dictList)) {
            //更新缓存
            String dictType = dictList.get(0).getDictType();
            DictUtils.setDictCache(dictType,dictDataService.list(dictDataService.lambdaQuery().eq(SysDictData::getDictType,dictType)));
        }
        return CommonResult.success();
    }

    @ApiOperation("获取字典缓存")
    @GetMapping("cache")
    public CommonResult<List<DictCacheListVo>> cache(){
        return CommonResult.success(dictDataService.getCache());
    }
}
